import React, { useEffect, useMemo, useRef, useState } from 'react'
import styles from './shop1.module.css'
import { Cell, Tag, Tabs, Button, Rate, Radio, Checkbox, Stepper, Popup } from 'react-vant';
import { Card } from '@nutui/nutui-react'
import { ArrowDown, GoodJobO, LocationO, PhoneO,Passed } from '@react-vant/icons';
import { SideBar } from 'antd-mobile'
import { useSelector, useDispatch } from 'react-redux';
import { useMap, useThrottleFn } from 'ahooks'
import { addList, jianList } from '../../redux2/modules/cart'
import axios from 'axios';
import { http } from '../../utils'
export default function Shop1() {

    const [show, setshow] = useState(0)

    const huan = (e) => {
        setshow(e.name)
    }
    const [list, setlist] = useState([])
    const [type, settype] = useState([])
    
    const dispatch = useDispatch()
    const history = useSelector((store) => store.carts.historyList)
    const ids = useSelector((store) => store.carts.ids)
    const getType = async () => {
        let res = await http.get('/xzx/type')
        settype(res.data)
    }
    const getList = async () => {
        let res = await http.get('/xzx/shop')
        setlist(res.data)
    }
    const [state, setState] = useState('')
    const onClose = () => setState('')
    const [activeKey, setActiveKey] = useState('67b4647d7c5e12eec6c0f13f')

    const { run: handleScroll } = useThrottleFn(
        () => {
            let currentKey = type[0]._id
            for (const item of type) {
                const element = document.getElementById(`anchor-${item._id}`)
                if (!element) continue
                const rect = element.getBoundingClientRect()
                if (rect.top <= 0) {
                    currentKey = item._id
                } else {
                    break
                }
            }
            setActiveKey(currentKey)
        },
        {
            leading: true,
            trailing: true,
            wait: 100,
        }
    )

    const mainElementRef = useRef(null)

    useEffect(() => {
        const mainElement = mainElementRef.current
        if (!mainElement) return
        mainElement.addEventListener('scroll', handleScroll)
        return () => {
            mainElement.removeEventListener('scroll', handleScroll)
        }
    }, [])
    //计算数量
    const total = useMemo(() => {
        return history.length
    })

    //计算价钱
    const handAdd = (item) => {
        dispatch(addList(item))
    }
    const handJian = (item) => {
        dispatch(jianList(item))
    }

    const [value8, setValue8] = useState(0)
    const sum = useMemo(() => {
        let sum = 0
        history.forEach(item => {
            sum += item.price * item.counts
        })
        return sum
    })
    const cha = useMemo(() => {
        return 20 - sum
    })
    useEffect(() => {
        getList(),
            getType()
        console.log(ids);
    }, [])
    return (
        <div className={styles.big}>
            <div className={styles.top}>
                <div className={styles.top_img} />
            </div>



            <div className={styles.bot}>
                <div className={styles.bot_big}>
                    <div className={styles.bot_top}>
                        <div className={styles.bot_top_left}>
                            <span style={{ fontWeight: 'bold', fontSize: '.19rem' }}>华莱士·全鸡汉堡-保定爱情广场</span>
                            <span style={{ fontSize: '.14rem' }}>
                                <Tag color="#ffe1e1" textColor="#ff644d">平台专送</Tag>&nbsp;30分钟&nbsp;月售312&nbsp;人均￥45&nbsp;可自取
                            </span>
                            <span className={styles.bot_top_send}>
                                <Tag color="#ff644d" plain>50减3</Tag>
                                <Tag color="#ff644d" plain>100减6</Tag>
                                <Tag color="#ff644d" plain>150减10</Tag>
                            </span>
                        </div>
                        <img src="/cry2.svg" alt="" />
                    </div>
                    <div className={styles.bot_out}>
                        <span>公告：华莱士全集汉堡，全国门店一万家，我家最好吃...</span>
                        <ArrowDown color='#999' fontSize='.1rem' />
                    </div>
                    <div className={styles.bot_tab}>
                        <div className={styles.bot_tab_left}>
                            <Tabs defaultActive={show} color='#ff644d' onClickTab={(e) => { huan(e) }}>
                                <Tabs.TabPane key='1' title='点餐' />
                                <Tabs.TabPane key='1' title='评价' />
                                <Tabs.TabPane key='1' title='商家' />
                            </Tabs>
                        </div>
                        <div className={styles.bot_tab_but}>团购优惠</div>
                    </div>
                    {
                        show == 0 ?
                            <div>
                                <img src="/cry3.svg" alt="" width='94%' style={{ marginTop: '.2rem' }} />
                                <div className={styles.container}>
                                    <div className={styles.side}>
                                        <SideBar
                                            activeKey={activeKey}
                                            onChange={key => {
                                                document.getElementById(`anchor-${key}`)?.scrollIntoView()
                                            }}
                                        >
                                            {type.map(item => (
                                                <SideBar.Item key={item._id} title={item.name} />
                                            ))}
                                        </SideBar>
                                    </div>
                                    <div className={styles.main} ref={mainElementRef}>
                                        {type.map(items => (
                                            <div key={items._id} >
                                                <h2 id={`anchor-${items._id}`}>{items.name}</h2>
                                                {
                                                    list.map((item, index) => {
                                                        return (
                                                            (items._id == item.tid && item.issale == true) && <Card

                                                                style={{ margin: '0.3rem 0rem' }}
                                                                src={item.img}
                                                                title={item.name}
                                                                price={item.price}
                                                                description={
                                                                    <>
                                                                        <p>库存{item.count}</p>
                                                                        <p style={{ fontSize: '0.15rem' }}>月售6</p>
                                                                    </>
                                                                }
                                                                extra={<div style={{ marginLeft: '0.6rem', width: '1rem' }} >
                                                                    {/* <img src="/imgs/shop1.svg" alt="" onClick={()=>handAdd(item)}/> */}
                                                                    {ids.includes(item._id) ? <Passed /> : <img src="/low1.svg" alt="" onClick={() => handAdd(item)} />}

                                                                </div>}
                                                            />
                                                        )
                                                    })
                                                }
                                            </div>
                                        ))}
                                    </div>
                                    <div className={styles.foot} onClick={() => {
                                        setState('bottom')
                                        console.log(111);
                                    }}>
                                        <div style={{ position: 'relative', marginTop: '0.2rem' }}>
                                            <img src='/low2.svg' alt="" />
                                            <p style={{ position: 'absolute', top: '-0.1rem', right: '0rem', borderRadius: '50%', backgroundColor: "white", color: "red", width: '0.2rem', textAlign: 'center' }}>{total}</p>
                                        </div>

                                        <div style={{ marginRight: '0.3rem' }}>
                                            <p>￥{sum}</p>
                                            <p>另需配送费￥4</p>
                                        </div>
                                        <p style={{ fontSize: "0.15rem", color: 'rgb(128, 128, 128)', marginLeft: '0.2rem' }}>{cha > 0 ? cha : 0}元起送</p>

                                    </div>
                                    <Popup
                                        visible={state === 'bottom'}
                                        style={{ height: '50%' }}
                                        position='bottom'
                                        onClose={onClose}
                                    >
                                        {history.map((item, index) => {
                                            return (
                                                <Card

                                                    style={{ margin: '0.3rem 0rem', marginLeft: '0.1rem' }}
                                                    src={item.img}
                                                    title={item.name}
                                                    price={item.price}
                                                    description={
                                                        <>
                                                            <p>库存{item.count}</p>
                                                            <p style={{ fontSize: '0.15rem' }}>月售6</p>
                                                        </>
                                                    }
                                                    extra={<div style={{ marginLeft: '0.6rem', width: '1rem' }} >
                                                        <Stepper
                                                            onOverlimit={() => console.log('overlimit')}
                                                            value={item.counts}
                                                            onMinus={() => handJian(item)}
                                                            onPlus={() => handAdd(item)}
                                                            onChange={v => console.log(v)}
                                                        />
                                                    </div>}
                                                />
                                            )
                                        })}

                                    </Popup>
                                </div>
                            </div>

                            : ''
                    }

                </div>
                {
                    show == 1 ?
                        <div className={styles.bot_botts}>
                            <div className={styles.bot_count}>
                                <div className={styles.bot_count_top}>
                                    <span style={{ color: '#fe5529', fontSize: '.4rem', fontWeight: 'bold' }}>4.5</span>
                                    <div className={styles.bot_count_right}>
                                        <div className={styles.bot_count_rtop}>
                                            <span>商家评分</span>&emsp;&emsp;&emsp;&nbsp;
                                            <span>味道</span>&emsp;
                                            <span>包装</span>&emsp;&nbsp;
                                            <span>配送满意度</span>
                                        </div>
                                        <div className={styles.bot_count_bom}>
                                            <Rate value='1' size='.17rem' />&nbsp;&nbsp;&nbsp;
                                            <span>4.4</span>&emsp;&nbsp;
                                            <span>4.7</span>&emsp;&nbsp;
                                            <span>98%</span>
                                        </div>
                                    </div>
                                </div>
                                <div className={styles.bot_count_cent}>
                                    <div id={styles.count_clic}>全部&nbsp;405</div>
                                    <div>最新</div>
                                    <div>好评&nbsp;435</div>
                                    <div>差评&nbsp;405</div>
                                    <div>有图&nbsp;405</div>
                                    <div>商家回复&nbsp;405</div>
                                </div>
                                <div className={styles.bot_count_bots}>
                                    <Checkbox defaultChecked checkedColor='#ff644d' iconSize='.15rem' />&nbsp;只看有内容的评价
                                </div>
                            </div>
                            <div className={styles.bot_seek}>
                                <div className={styles.bot_seek_top}>
                                    <div className={styles.bot_seek_tbig}>
                                        <img src="/cry4.svg" alt="" />
                                        <div className={styles.bot_seek_name}>
                                            <span style={{ fontWeight: 'bold' }}>匿名用户</span>
                                            <span style={{ color: '#999', fontSize: '.15rem' }}>2025-10-05</span>
                                        </div>
                                    </div>
                                    <span style={{ fontSize: '.14rem', color: '#999', display: 'flex', alignItems: 'center' }}>有用10&nbsp;<GoodJobO /></span>
                                </div>
                                <div className={styles.bot_seek_score}>
                                    <Rate value='1' size='.17rem' /><span style={{ fontSize: '.14rem', color: '#999' }}>&nbsp;&nbsp;好</span>
                                </div>
                                <div className={styles.bot_seek_font}>
                                    一如既往的不错，比较清淡，适合南方人口味，麦香鸡排汉堡值得推荐。
                                </div>
                                <div className={styles.bot_seek_img}>
                                    <img src="/cry4.svg" alt="" />
                                    <div>
                                        <img src="/cry5.svg" alt="" />
                                        <img src="/cry6.svg" alt="" />
                                    </div>
                                </div>
                            </div>
                        </div>


                        : ''
                }
                {
                    show == 2 ?
                        <div className={styles.bot_botts}>
                            <div className={styles.bot_home}>
                                <span style={{ fontWeight: 'bold' }}>华莱士·全鸡汉堡-爱情广场店</span>
                                <div className={styles.bot_home_local}>
                                    <LocationO />
                                    <div style={{ fontSize: '.16rem', color: '#999' }}>保定市莲池区南二环南大园乡爱情广场1956号</div>
                                    <PhoneO fontSize='20rem' color='#ff644d' />
                                </div>
                            </div>
                            <div className={styles.bot_home_massage}>
                                <span style={{ fontWeight: 'bold', color: 'black', fontSize: '.16rem' }}>商家信息</span>
                                <span>商家品类：汉堡薯条/炸鸡炸串</span>
                                <span>堂食时段：11:30-13:30,17:30-19:30</span>
                                <span>外卖时段：10:00-23:59</span>
                                <span>自取时段：11:30-13:30,17:30-19:30</span>
                                <span>配送服务：<Tag color="#ffe1e1" textColor="#ff644d">平台专送</Tag></span>
                                <span>商家服务：可开发票</span>
                            </div>
                            <div className={styles.bot_home_look}>
                                查看商家资质信息
                            </div>
                        </div> : ''
                }
            </div>
        </div>
    )
}
